/*
 * @Description: app接单首页    AppHomePage
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-10-12 09:22:57
 * @LastAuthor   : zhengzhuang
 * @lastTime     : 2019-12-23 11:35:55
 */
import 'dart:async';
import 'dart:collection';
import 'dart:io';

import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:C20Driver/model/get_driver_statistics_date.dart';
import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/provider/record_provider.dart';
import 'package:C20Driver/service/mqtt_manage.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:C20Driver/utils/record_util.dart';
import 'package:C20Driver/utils/utils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'dispatch_order_list.dart';
import 'package:intl/intl.dart' show DateFormat;

class AppHomePage extends StatefulWidget {
  @override
  _AppHomePageState createState() => _AppHomePageState();
}

class _AppHomePageState extends State<AppHomePage> {
  GetDriverStatisticsDate _todayData;
  var clientId;
  Record record;

  @override
  void initState() {
    super.initState();

    _getDriverStatisticsFun();
    clientId = MqttManage.getInstance().getClientId;
    // //扫描是否有录音文件
    queryLocalRecordFile(clientId);
  }

  /// 获取车主当日数据
  Future<void> _getDriverStatisticsFun() async {
    _todayData = await Request.getDriverStatisticsFun(context);
    setState(() {
      _todayData = _todayData;
    });
    _setLocationCity();
    return _todayData;
  }

  Future _setLocationCity() async {
    if (await PermissionHandlerX.position(context)) {
      /// 获取我的定位
      AmapLocation.fetchLocation().then((res) {
        Provider.of<PositionInformation>(context, listen: false)
            .setCityName(res.city);
        Provider.of<PositionInformation>(context, listen: false)
            .setRealtimeDriverPosition(
                context, res.latLng.latitude, res.latLng.longitude, '');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(bottom: ScreenUtil().setWidth(25)),
            child: RefreshIndicator(
              onRefresh: () => _getDriverStatisticsFun(),
              color: Colors.black,
              child: ListView(
                children: <Widget>[
                  _statisticsWidget(context),
                  // SizedBox(height: ScreenUtil().setWidth(10.0)),
                  propagandaBanner(context),
                  SizedBox(height: ScreenUtil().setWidth(30.0)),
                  DispatchOrderList(),
                ],
              ),
            ),
          ),
          Positioned(
            bottom: 10,
            left: 0,
            child: _dispatchReceipt(context),
          ),
        ],
      ),
    );
  }

  void printFiles(String path) {
    try {
      var dir = new Directory(path);
      List<FileSystemEntity> files = dir.listSync();
      for (var f in files) {
        if (f.path.endsWith("aac")) {
          print("f.path${f.path}");
          // f.deleteSync();
        }
      }
    } catch (e) {
      print("目录不存在！");
    }
  }

  /// 统计组件
  Widget _statisticsWidget(context) {
    return Container(
      alignment: Alignment.center,
      width: double.infinity,
      height: ScreenUtil().setWidth(250.0),
      decoration: BoxDecoration(
        color: Colors.white,
        gradient: LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [
            Color(0xff697794),
            Color(0xff374258),
          ],
        ),
      ),
      child: Container(
        width: ScreenUtil().setWidth(686),
        height: ScreenUtil().setWidth(154),
        decoration: BoxDecoration(
          color: Color(0x22ffffff),
          borderRadius: BorderRadius.all(Radius.circular(20)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            _statisticsList(
                _todayData != null ? _todayData.todayDealRate : '', '今日成交'),
            InkWell(
              child: _statisticsList(
                  _todayData != null ? _todayData.todayIncome : '', '今日收入'),
              // onTap: () => NavigatorUtil.jump(context, '/myIncomeRecord'),
            ),
            InkWell(
              child: _statisticsList(
                  _todayData != null ? _todayData.todayOrderNum : '', '今日接单'),
              // onTap: () =>
              //     NavigatorUtil.jump(context, '/orderStatistics'),
            ),
          ],
        ),
      ),
    );
  }

  /// 统计数据列表
  Widget _statisticsList(String title, String des) {
    return Container(
      width: ScreenUtil().setWidth(145.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _statisticsTitle(title),
          SizedBox(
            height: ScreenUtil().setWidth(20.0),
          ),
          _statisticsDes(des),
        ],
      ),
    );
  }

  /// 统计数据title
  Widget _statisticsTitle(title) {
    return Text(
      title != null ? title : 0,
      maxLines: 1,
      style: TextStyle(
        fontSize: ScreenUtil().setSp(36.0),
        color: Colors.white,
        fontWeight: FontWeight.w500,
      ),
    );
  }

  /// 统计数据描述
  Widget _statisticsDes(title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: ScreenUtil().setSp(28.0),
        color: Color(0xbbffffff),
        fontWeight: FontWeight.w700,
      ),
    );
  }

  /// 宣传banner
  Widget propagandaBanner(context) {
    return InkWell(
      child: Container(
        width: double.infinity,
        height: ScreenUtil().setWidth(300.0),
        child: ClipRRect(
          child: Image.asset(
            'assets/icon/home_advertising.png',
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.fitWidth,
          ),
        ),
        padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(32),
          right: ScreenUtil().setWidth(32),
        ),
        color: Colors.transparent,
      ),
      // onTap: () => NavigatorUtil.jump(context, '/inviteGoodFriends'),
      onTap: () {},
    );
  }

  /// 底部出车接单
  _dispatchReceipt(context) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(30.0),
          right: ScreenUtil().setWidth(30.0)),
      width: ScreenUtil().setWidth(750.0),
      height: ScreenUtil().setWidth(140.0),
      color: Colors.white,
      child: Row(
        children: <Widget>[
          MaterialButton(
            elevation: 0,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(49))),
            minWidth: ScreenUtil().setWidth(150.0),
            height: ScreenUtil().setWidth(98),
            color: Color(0xffEEF6EE),
            textColor: Colors.white,
            child: _buttonText('模式'),
            onPressed: () => NavigatorUtil.jump(context, '/orderModeSettings'),
          ),
          SizedBox(width: ScreenUtil().setWidth(20.0)),
          _exitStatus(),
        ],
      ),
    );
  }

  /// button 字体
  Widget _buttonText(title) {
    return Text(
      title,
      style: TextStyle(
          color: Color(0xff668D6E),
          fontSize: ScreenUtil().setSp(32.0),
          fontWeight: FontWeight.w500),
    );
  }

  /// 出车状态
  _exitStatus() {
    DriverInformation driverInformation =
        Provider.of<DriverInformation>(context, listen: false);
    if (driverInformation.driverInfo.workingStatus == '0020') {
      return _launched();
    } else if (driverInformation.driverInfo.workingStatus == '0030') {
      return _notAtWork();
    } else if (driverInformation.driverInfo.workingStatus == '0040') {
      return _launched();
    } else {
      return Container();
    }
  }

  /// 未出车
  Widget _notAtWork() {
    return Expanded(
      child: MaterialButton(
        minWidth: ScreenUtil().setWidth(150.0),
        elevation: 0,
        child: Container(
          height: ScreenUtil().setWidth(98),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [
                Color(0xff3FB956),
                Color(0xff65CA00),
              ],
            ),
            borderRadius: BorderRadius.all(
              Radius.circular(ScreenUtil().setWidth(50)),
            ),
          ),
          alignment: Alignment.center,
          child: Text(
            '点击接单',
            style: TextStyle(
                color: Color(0xffffffff),
                fontSize: ScreenUtil().setSp(32),
                fontWeight: FontWeight.w500),
          ),
        ),
        onPressed: () => Utils.setFaceRecognition(context),
      ),
    );
  }

  /// 出车中
  Widget _launched() {
    return Expanded(
      child: Row(
        children: <Widget>[
          Expanded(
            child: MaterialButton(
              minWidth: ScreenUtil().setWidth(150.0),
              elevation: 0,
              onPressed: () {},
              child: Container(
                height: ScreenUtil().setWidth(98),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      Color(0xff3FB956),
                      Color(0xff65CA00),
                    ],
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(ScreenUtil().setWidth(50)),
                  ),
                ),
                alignment: Alignment.center,
                child: Consumer<DriverInformation>(
                  builder: (ctx, state, child) {
                    return Text(
                      state.driverInfo.workingStatus == '0040'
                          ? '订单进行中'
                          : '听单中...',
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(32.0),
                        fontWeight: FontWeight.w500,
                        color: Color(0xffffffff),
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
          MaterialButton(
            elevation: 0,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(49))),
            minWidth: ScreenUtil().setWidth(150.0),
            height: ScreenUtil().setWidth(98),
            color: Color(0xffEEF6EE),
            textColor: Colors.white,
            child: _buttonText('收车'),
            onPressed: () => Utils.setWorkimgStatus(context),
          ),
        ],
      ),
    );
  }

  ///查询本地是否有未上传的,有文件就上传
  void queryLocalRecordFile(String clientId) async {
    record = new Record();
    Directory directory = await getApplicationDocumentsDirectory();
    List<File> recordList = record.printFiles(directory.path);
    recordList.forEach((element) {
      print("valuesss element${element.path}");
      Request.genUptoken(clientId: clientId, defaultFix: "aac").then((value) {
        print("value${value}");
        if (value != null) {
          List dates = value['tokenList'] as List;
          var key = dates.first["resourceKey"];
          var upLoadToken = dates.first["token"];
          print("value key${key}");
          print("value upLoadToken${upLoadToken}");
          Request.qiniuUpload(
                  key: key, uploadToken: upLoadToken, file: element.path)
              .then((value) {
            print("valuesss2${element.path}");
            if (value != null) {
              getApplicationDocumentsDirectory().then((value) {
                print("value  dele${value}");
                record.deleteFiles(value.path);
              });
            }
          });
        }
      });
    });
  }
}
